Language Translation

In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset of English and French sentences that can translate new sentences from English to French.

Get the Data

Since translating the whole language of English to French will take lots of time to train, we have provided you with a small portion of the English corpus.


In [1]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import helper
import problem_unittests as tests

source_path = 'data/small_vocab_en'
target_path = 'data/small_vocab_fr'
source_text = helper.load_data(source_path)
target_text = helper.load_data(target_path)

Explore the Data

Play around with view_sentence_range to view different parts of the data.


In [2]:
view_sentence_range = (0, 10)

"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import numpy as np

print('Dataset Stats')
print('Roughly the number of unique words: {}'.format(len({word: None for word in source_text.split()})))

sentences = source_text.split('\n')
word_counts = [len(sentence.split()) for sentence in sentences]
print('Number of sentences: {}'.format(len(sentences)))
print('Average number of words in a sentence: {}'.format(np.average(word_counts)))

print()
print('English sentences {} to {}:'.format(*view_sentence_range))
print('\n'.join(source_text.split('\n')[view_sentence_range[0]:view_sentence_range[1]]))
print()
print('French sentences {} to {}:'.format(*view_sentence_range))
print('\n'.join(target_text.split('\n')[view_sentence_range[0]:view_sentence_range[1]]))


Dataset Stats
Roughly the number of unique words: 227
Number of sentences: 137861
Average number of words in a sentence: 13.225277634719028

English sentences 0 to 10:
new jersey is sometimes quiet during autumn , and it is snowy in april .
the united states is usually chilly during july , and it is usually freezing in november .
california is usually quiet during march , and it is usually hot in june .
the united states is sometimes mild during june , and it is cold in september .
your least liked fruit is the grape , but my least liked is the apple .
his favorite fruit is the orange , but my favorite is the grape .
paris is relaxing during december , but it is usually chilly in july .
new jersey is busy during spring , and it is never hot in march .
our least liked fruit is the lemon , but my least liked is the grape .
the united states is sometimes busy during january , and it is sometimes warm in november .

French sentences 0 to 10:
new jersey est parfois calme pendant l' automne , et il est neigeux en avril .
les états-unis est généralement froid en juillet , et il gèle habituellement en novembre .
california est généralement calme en mars , et il est généralement chaud en juin .
les états-unis est parfois légère en juin , et il fait froid en septembre .
votre moins aimé fruit est le raisin , mais mon moins aimé est la pomme .
son fruit préféré est l'orange , mais mon préféré est le raisin .
paris est relaxant en décembre , mais il est généralement froid en juillet .
new jersey est occupé au printemps , et il est jamais chaude en mars .
notre fruit est moins aimé le citron , mais mon moins aimé est le raisin .
les états-unis est parfois occupé en janvier , et il est parfois chaud en novembre .

Implement Preprocessing Function

Text to Word Ids

As you did with other RNNs, you must turn the text into a number so the computer can understand it. In the function text_to_ids(), you'll turn source_text and target_text from words to ids. However, you need to add the <EOS> word id at the end of target_text. This will help the neural network predict when the sentence should end.

You can get the <EOS> word id by doing:

target_vocab_to_int['<EOS>']

You can get other word ids using source_vocab_to_int and target_vocab_to_int.


In [3]:
def text_to_ids(source_text, target_text, source_vocab_to_int, target_vocab_to_int):
    """
    Convert source and target text to proper word ids
    :param source_text: String that contains all the source text.
    :param target_text: String that contains all the target text.
    :param source_vocab_to_int: Dictionary to go from the source words to an id
    :param target_vocab_to_int: Dictionary to go from the target words to an id
    :return: A tuple of lists (source_id_text, target_id_text)
    """
    
    eos = target_vocab_to_int['<EOS>']

    source_sentences = [s for s in source_text.split('\n')]
    target_sentences = [s for s in target_text.split('\n')]
    
    #print(eos)
    #print(source_sentences)
    #print(target_sentences)
    
    source_id_text = [[source_vocab_to_int[w] for w in s.split()] for s in source_sentences]
    target_id_text = [[target_vocab_to_int[w] for w in s.split()] + [eos] for s in target_sentences]
            
    return source_id_text, target_id_text

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_text_to_ids(text_to_ids)


Tests Passed

Preprocess all the data and save it

Running the code cell below will preprocess all the data and save it to file.


In [4]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
helper.preprocess_and_save_data(source_path, target_path, text_to_ids)

Check Point

This is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk.


In [5]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import numpy as np
import helper
import problem_unittests as tests

(source_int_text, target_int_text), (source_vocab_to_int, target_vocab_to_int), _ = helper.load_preprocess()

Check the Version of TensorFlow and Access to GPU

This will check to make sure you have the correct version of TensorFlow and access to a GPU


In [6]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
from distutils.version import LooseVersion
import warnings
import tensorflow as tf
from tensorflow.python.layers.core import Dense

# Check TensorFlow Version
assert LooseVersion(tf.__version__) >= LooseVersion('1.1'), 'Please use TensorFlow version 1.1 or newer'
print('TensorFlow Version: {}'.format(tf.__version__))

# Check for a GPU
if not tf.test.gpu_device_name():
    warnings.warn('No GPU found. Please use a GPU to train your neural network.')
else:
    print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))


TensorFlow Version: 1.1.0
/opt/conda/lib/python3.6/site-packages/ipykernel_launcher.py:15: UserWarning: No GPU found. Please use a GPU to train your neural network.
  from ipykernel import kernelapp as app

Build the Neural Network

You'll build the components necessary to build a Sequence-to-Sequence model by implementing the following functions below:

  • model_inputs
  • process_decoder_input
  • encoding_layer
  • decoding_layer_train
  • decoding_layer_infer
  • decoding_layer
  • seq2seq_model

Input

Implement the model_inputs() function to create TF Placeholders for the Neural Network. It should create the following placeholders:

  • Input text placeholder named "input" using the TF Placeholder name parameter with rank 2.
  • Targets placeholder with rank 2.
  • Learning rate placeholder with rank 0.
  • Keep probability placeholder named "keep_prob" using the TF Placeholder name parameter with rank 0.
  • Target sequence length placeholder named "target_sequence_length" with rank 1
  • Max target sequence length tensor named "max_target_len" getting its value from applying tf.reduce_max on the target_sequence_length placeholder. Rank 0.
  • Source sequence length placeholder named "source_sequence_length" with rank 1

Return the placeholders in the following the tuple (input, targets, learning rate, keep probability, target sequence length, max target sequence length, source sequence length)


In [7]:
def model_inputs():
    """
    Create TF Placeholders for input, targets, learning rate, and lengths of source and target sequences.
    :return: Tuple (input, targets, learning rate, keep probability, target sequence length,
    max target sequence length, source sequence length)
    """
    input_data = tf.placeholder(tf.int32, [None, None], name='input')
    targets = tf.placeholder(tf.int32, [None, None], name='target')
    learning_rate = tf.placeholder(tf.float32, name='learning_rate')
    keep_probability = tf.placeholder(tf.float32, None, name='keep_prob')
    target_squence_length = tf.placeholder(tf.int32, (None,), name='target_sequence_length')
    max_target_sequence_length = tf.reduce_max(target_squence_length, name='max_target_len')
    source_sequence_length = tf.placeholder(tf.int32, (None,), name='source_sequence_length')
    
    return (input_data, 
            targets, 
            learning_rate, 
            keep_probability, 
            target_squence_length, 
            max_target_sequence_length, 
            source_sequence_length)

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_inputs(model_inputs)


Tests Passed

Process Decoder Input

Implement process_decoder_input by removing the last word id from each batch in target_data and concat the GO ID to the begining of each batch.


In [8]:
def process_decoder_input(target_data, target_vocab_to_int, batch_size):
    """
    Preprocess target data for encoding
    :param target_data: Target Placehoder
    :param target_vocab_to_int: Dictionary to go from the target words to an id
    :param batch_size: Batch Size
    :return: Preprocessed target data
    """
    ending = tf.strided_slice(target_data, [0, 0], [batch_size, -1], [1, 1])
    dec_input = tf.concat([tf.fill([batch_size, 1], target_vocab_to_int['<GO>']), ending], 1)
    return dec_input

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_process_encoding_input(process_decoder_input)


Tests Passed

Encoding

Implement encoding_layer() to create a Encoder RNN layer:

from imp import reload reload(tests) def encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob, source_sequence_length, source_vocab_size, encoding_embedding_size): """ Create encoding layer :param rnn_inputs: Inputs for the RNN :param rnn_size: RNN Size :param num_layers: Number of layers :param keep_prob: Dropout keep probability :param source_sequence_length: a list of the lengths of each sequence in the batch :param source_vocab_size: vocabulary size of source data :param encoding_embedding_size: embedding size of source data :return: tuple (RNN output, RNN state) """ This is from the sequence 2 secuqnce lesson. It doesn't quite do the stacked thing stated up # Encoder embedding enc_embed_input = tf.contrib.layers.embed_sequence(rnn_inputs, source_vocab_size, encoding_embedding_size) # RNN cell def make_cell(rnn_size): enc_cell = tf.contrib.rnn.LSTMCell(rnn_size, initializer=tf.random_uniform_initializer(-0.1, 0.1, seed=2)) return enc_cell enc_cell = tf.contrib.rnn.MultiRNNCell([make_cell(rnn_size) for _ in range(num_layers)]) enc_output, enc_state = tf.nn.dynamic_rnn(enc_cell, enc_embed_input, sequence_length=source_sequence_length, dtype=tf.float32) return enc_output, enc_state """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_encoding_layer(encoding_layer)
Stacking multiple LSTMs To give the model more expressive power, we can add multiple layers of LSTMs to process the data. The output of the first layer will become the input of the second and so on. We have a class called MultiRNNCell that makes the implementation seamless: def lstm_cell(): return tf.contrib.rnn.BasicLSTMCell(lstm_size) stacked_lstm = tf.contrib.rnn.MultiRNNCell([lstm_cell() for _ in range(number_of_layers)]) initial_state = state = stacked_lstm.zero_state(batch_size, tf.float32) for i in range(num_steps): # The value of state is updated after processing each batch of words. output, state = stacked_lstm(words[:, i], state) # The rest of the code. # ... final_state = state

In [9]:
def make_stacked_lstm_rnn_cell(rnn_size, num_layers, keep_prob):

    def rnn_cell(rnn_size):
        
        # Construct a stacked tf.contrib.rnn.LSTMCell 
        # __init__(num_units, use_peepholes=False, cell_clip=None, initializer=None,
        # num_proj=None, proj_clip=None, num_unit_shards=None, num_proj_shards=None,
        # forget_bias=1.0, state_is_tuple=True, activation=None, reuse=None)
        lstm_cell = tf.contrib.rnn.LSTMCell(rnn_size, initializer=tf.random_uniform_initializer(-0.1, 0.1, seed=2)) 
        
        # wrapped in a tf.contrib.rnn.DropoutWrapper
        # __init__(cell, input_keep_prob=1.0, output_keep_prob=1.0, state_keep_prob=1.0,
        # variational_recurrent=False, input_size=None, dtype=None, seed=None)
        return tf.contrib.rnn.DropoutWrapper(lstm_cell, keep_prob, keep_prob, keep_prob)

    # stacked_lstm = tf.contrib.rnn.MultiRNNCell([lstm_cell() for _ in range(number_of_layers)])
    stacked_lstm_cell = tf.contrib.rnn.MultiRNNCell([rnn_cell(rnn_size) for _ in range(num_layers)])

    return stacked_lstm_cell

In [10]:
from imp import reload
reload(tests)

def encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob, 
                   source_sequence_length, source_vocab_size, 
                   encoding_embedding_size):
    """
    Create encoding layer
    :param rnn_inputs: Inputs for the RNN
    :param rnn_size: RNN Size
    :param num_layers: Number of layers
    :param keep_prob: Dropout keep probability
    :param source_sequence_length: a list of the lengths of each sequence in the batch
    :param source_vocab_size: vocabulary size of source data
    :param encoding_embedding_size: embedding size of source data
    :return: tuple (RNN output, RNN state)
    """
    
    # Encoder embedding - Embed the encoder input using tf.contrib.layers.embed_sequence
    # embed_sequence(ids, vocab_size=None, embed_dim=None, unique=False, initializer=None, regularizer=None, trainable=True, scope=None, reuse=None)
    # Returns: Tensor of [batch_size, doc_length, embed_dim] with embedded sequences.'''
    enc_embed_input = tf.contrib.layers.embed_sequence(rnn_inputs, source_vocab_size, encoding_embedding_size)
     
    # Construct a stacked tf.contrib.rnn.LSTMCell wrapped in a tf.contrib.rnn.DropoutWrapper
    stacked_cell = make_stacked_lstm_rnn_cell(rnn_size, num_layers, keep_prob)   
    
    # Pass cell and embedded input to tf.nn.dynamic_rnn()
    # dynamic_rnn(cell, inputs, sequence_length=None, initial_state=None, dtype=None, parallel_iterations=None, swap_memory=False, time_major=False, scope=None)
    # Returns: A pair (outputs, state) 
    return tf.nn.dynamic_rnn(stacked_cell, enc_embed_input, sequence_length=source_sequence_length, dtype=tf.float32)

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_encoding_layer(encoding_layer)


Tests Passed

Decoding - Training

Create a training decoding layer:


In [11]:
def decoding_layer_train(encoder_state, dec_cell, dec_embed_input, 
                         target_sequence_length, max_summary_length, 
                         output_layer, keep_prob):
    """
    Create a decoding layer for training
    :param encoder_state: Encoder State
    :param dec_cell: Decoder RNN Cell
    :param dec_embed_input: Decoder embedded input
    :param target_sequence_length: The lengths of each sequence in the target batch
    :param max_summary_length: The length of the longest sequence in the batch
    :param output_layer: Function to apply the output layer
    :param keep_prob: Dropout keep probability
    :return: BasicDecoderOutput containing training logits and sample_id
    """
    
    # Create a tf.contrib.seq2seq.TrainingHelper
    # __init__(inputs, sequence_length, time_major=False, name=None)
    training_helper = tf.contrib.seq2seq.TrainingHelper(inputs=dec_embed_input,
                                                        sequence_length=target_sequence_length,
                                                        time_major=False)
    # Create a tf.contrib.seq2seq.BasicDecoder
    # __init__(cell, helper, initial_state, output_layer=None)
    training_decoder = tf.contrib.seq2seq.BasicDecoder(dec_cell, training_helper, encoder_state, output_layer)
    
    # Obtain the decoder outputs from tf.contrib.seq2seq.dynamic_decode
    # dynamic_decode(decoder, output_time_major=False, impute_finished=False, maximum_iterations=None, parallel_iterations=32, swap_memory=False, scope=None)
    # Returns: (final_outputs, final_state, final_sequence_lengths)
    training_decoder_output, _ = tf.contrib.seq2seq.dynamic_decode(training_decoder, impute_finished=True,
                                                                   maximum_iterations=max_summary_length)
        
    return training_decoder_output

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_decoding_layer_train(decoding_layer_train)


Tests Passed

Decoding - Inference

Create inference decoder:


In [12]:
def decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, start_of_sequence_id,
                         end_of_sequence_id, max_target_sequence_length,
                         vocab_size, output_layer, batch_size, keep_prob):
    """
    Create a decoding layer for inference
    :param encoder_state: Encoder state
    :param dec_cell: Decoder RNN Cell
    :param dec_embeddings: Decoder embeddings
    :param start_of_sequence_id: GO ID
    :param end_of_sequence_id: EOS Id
    :param max_target_sequence_length: Maximum length of target sequences
    :param vocab_size: Size of decoder/target vocabulary
    :param decoding_scope: TenorFlow Variable Scope for decoding
    :param output_layer: Function to apply the output layer
    :param batch_size: Batch size
    :param keep_prob: Dropout keep probability
    :return: BasicDecoderOutput containing inference logits and sample_id
    """
    
    # Create a tf.contrib.seq2seq.GreedyEmbeddingHelper
    # __init__(embedding, start_tokens, end_token)
    # embedding: A callable that takes a vector tensor of ids (argmax ids), or the params argument for embedding_lookup. The returned tensor will be passed to the decoder input.
    # start_tokens: int32 vector shaped [batch_size], the start tokens.
    # end_token: int32 scalar, the token that marks end of decoding.
    start_tokens = tf.tile(tf.constant([start_of_sequence_id], dtype=tf.int32), [batch_size], name='start_tokens')
    inference_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(dec_embeddings, start_tokens, end_of_sequence_id)

    # Create a tf.contrib.seq2seq.BasicDecoder
    # __init__(cell, helper, initial_state, output_layer=None)
    # cell: An RNNCell instance.
    # helper: A Helper instance.
    # initial_state: A (possibly nested tuple of...) tensors and TensorArrays. The initial state of the RNNCell.
    # output_layer: (Optional) An instance of tf.layers.Layer, i.e., tf.layers.Dense. Optional layer to apply to the RNN output prior to storing the result or sampling.
    inference_decoder = tf.contrib.seq2seq.BasicDecoder(dec_cell, inference_helper, encoder_state, output_layer)

    # Obtain the decoder outputs from tf.contrib.seq2seq.dynamic_decode
    # dynamic_decode(decoder, output_time_major=False, impute_finished=False, maximum_iterations=None, parallel_iterations=32, swap_memory=False, scope=None)    
    # Returns: (final_outputs, final_state, final_sequence_lengths)
    decoder_output, _ = tf.contrib.seq2seq.dynamic_decode(inference_decoder, 
                                                          impute_finished=True, 
                                                          maximum_iterations=max_target_sequence_length)
    
    return decoder_output

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_decoding_layer_infer(decoding_layer_infer)


Tests Passed

Build the Decoding Layer

Implement decoding_layer() to create a Decoder RNN layer.

  • Embed the target sequences
  • Construct the decoder LSTM cell (just like you constructed the encoder cell above)
  • Create an output layer to map the outputs of the decoder to the elements of our vocabulary
  • Use the your decoding_layer_train(encoder_state, dec_cell, dec_embed_input, target_sequence_length, max_target_sequence_length, output_layer, keep_prob) function to get the training logits.
  • Use your decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, start_of_sequence_id, end_of_sequence_id, max_target_sequence_length, vocab_size, output_layer, batch_size, keep_prob) function to get the inference logits.

Note: You'll need to use tf.variable_scope to share variables between training and inference.


In [13]:
# Construct the decoder LSTM cell (just like you constructed the encoder cell above)
def decode_stacked_lstm_rnn_cell(rnn_size, num_layers, keep_prob=1.0): # remove keep_prob?

    def rnn_cell(rnn_size):
        
        # Construct a stacked tf.contrib.rnn.LSTMCell 
        # __init__(num_units, use_peepholes=False, cell_clip=None, initializer=None, 
        # num_proj=None, proj_clip=None, num_unit_shards=None, num_proj_shards=None, 
        # forget_bias=1.0, state_is_tuple=True, activation=None, reuse=None)
        lstm_cell = tf.contrib.rnn.LSTMCell(rnn_size, initializer=tf.random_uniform_initializer(-0.1, 0.1, seed=2))
        
        # wrapped in a tf.contrib.rnn.DropoutWrapper
        # __init__(cell, input_keep_prob=1.0, output_keep_prob=1.0, state_keep_prob=1.0, 
        # variational_recurrent=False, input_size=None, dtype=None, seed=None)
        # return tf.contrib.rnn.DropoutWrapper(lstm_cell, keep_prob, keep_prob, keep_prob)
        return lstm_cell

    # stacked_lstm = tf.contrib.rnn.MultiRNNCell([lstm_cell() for _ in range(number_of_layers)])
    decoded_lstm_cell = tf.contrib.rnn.MultiRNNCell([rnn_cell(rnn_size) for _ in range(num_layers)])

    return decoded_lstm_cell

In [15]:
def decoding_layer(dec_input, encoder_state,
                   target_sequence_length, max_target_sequence_length,
                   rnn_size,
                   num_layers, target_vocab_to_int, target_vocab_size,
                   batch_size, keep_prob, decoding_embedding_size):
    """
    Create decoding layer
    :param dec_input: Decoder input
    :param encoder_state: Encoder state
    :param target_sequence_length: The lengths of each sequence in the target batch
    :param max_target_sequence_length: Maximum length of target sequences
    :param rnn_size: RNN Size
    :param num_layers: Number of layers
    :param target_vocab_to_int: Dictionary to go from the target words to an id
    :param target_vocab_size: Size of target vocabulary
    :param batch_size: The size of the batch
    :param keep_prob: Dropout keep probability
    :param decoding_embedding_size: Decoding embedding size
    :return: Tuple of (Training BasicDecoderOutput, Inference BasicDecoderOutput)
    """
    # Embed the target sequences
    decoder_embeddings = tf.Variable(tf.random_uniform([target_vocab_size, decoding_embedding_size]))
    decoder_embeddings_input = tf.nn.embedding_lookup(decoder_embeddings, dec_input)
    
    # Construct the decoder LSTM cell (just like you constructed the encoder cell above)
    decoded_cell = decode_stacked_lstm_rnn_cell(rnn_size, num_layers) 
    
    # Create an output layer to map the outputs of the decoder to the elements of our vocabulary
    output_layer = Dense(target_vocab_size, 
                         kernel_initializer=tf.truncated_normal_initializer(mean=0.0, stddev=0.1))
    
    # Use the your decoding_layer_train(encoder_state, dec_cell, dec_embed_input, target_sequence_length, 
    # max_target_sequence_length, output_layer, keep_prob) function to get the training logits.
    with tf.variable_scope("decoding") as training_scope:
        training_logits = decoding_layer_train(encoder_state, decoded_cell, decoder_embeddings_input,
                                               target_sequence_length, max_target_sequence_length,
                                               output_layer, keep_prob)
    
    # Use your decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, start_of_sequence_id, 
    # end_of_sequence_id, max_target_sequence_length, vocab_size, output_layer, batch_size, keep_prob)
    # function to get the inference logits.
    start_of_sequence_id = target_vocab_to_int['<GO>']
    end_of_sequence_id = target_vocab_to_int['<EOS>']
    
    with tf.variable_scope("decoding", reuse=True) as inference_scope:
        inference_logits = decoding_layer_infer(encoder_state, decoded_cell, decoder_embeddings,
                                                start_of_sequence_id, end_of_sequence_id,
                                                max_target_sequence_length, target_vocab_size,
                                                output_layer, batch_size, keep_prob)
    
    return training_logits, inference_logits

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_decoding_layer(decoding_layer)


Tests Passed

Build the Neural Network

Apply the functions you implemented above to:

  • Encode the input using your encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob, source_sequence_length, source_vocab_size, encoding_embedding_size).
  • Process target data using your process_decoder_input(target_data, target_vocab_to_int, batch_size) function.
  • Decode the encoded input using your decoding_layer(dec_input, enc_state, target_sequence_length, max_target_sentence_length, rnn_size, num_layers, target_vocab_to_int, target_vocab_size, batch_size, keep_prob, dec_embedding_size) function.

In [18]:
def seq2seq_model(input_data, target_data, keep_prob, batch_size,
                  source_sequence_length, target_sequence_length,
                  max_target_sentence_length,
                  source_vocab_size, target_vocab_size,
                  enc_embedding_size, dec_embedding_size,
                  rnn_size, num_layers, target_vocab_to_int):
    """
    Build the Sequence-to-Sequence part of the neural network
    :param input_data: Input placeholder
    :param target_data: Target placeholder
    :param keep_prob: Dropout keep probability placeholder
    :param batch_size: Batch Size
    :param source_sequence_length: Sequence Lengths of source sequences in the batch
    :param target_sequence_length: Sequence Lengths of target sequences in the batch
    :param source_vocab_size: Source vocabulary size
    :param target_vocab_size: Target vocabulary size
    :param enc_embedding_size: Decoder embedding size
    :param dec_embedding_size: Encoder embedding size
    :param rnn_size: RNN Size
    :param num_layers: Number of layers
    :param target_vocab_to_int: Dictionary to go from the target words to an id
    :return: Tuple of (Training BasicDecoderOutput, Inference BasicDecoderOutput)
    """
    # Encode the input using your encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob, 
    # source_sequence_length, source_vocab_size, encoding_embedding_size).
    # Returns: A pair (outputs, state) 
    enc_output, enc_state = encoding_layer(input_data, rnn_size, num_layers, keep_prob,
                                           source_sequence_length, source_vocab_size, enc_embedding_size)
    
    # Process target data using your process_decoder_input(target_data, target_vocab_to_int, batch_size) function.
    # Returns: Preprocessed target data
    # ending = tf.strided_slice(target_data, [0, 0], [batch_size, -1], [1, 1])
    # return = tf.concat([tf.fill([batch_size, 1], target_vocab_to_int['<GO>']), ending], 1)
    dec_input = process_decoder_input(target_data, target_vocab_to_int, batch_size)
    
    # Decode the encoded input using your decoding_layer(dec_input, enc_state, target_sequence_length,
    # max_target_sentence_length, rnn_size, num_layers, target_vocab_to_int, target_vocab_size, 
    # batch_size, keep_prob, dec_embedding_size) function.
    # Returns: Tuple of (Training BasicDecoderOutput, Inference BasicDecoderOutput)
    training_output, inference_output = decoding_layer(dec_input, enc_state, target_sequence_length,
                                                       max_target_sentence_length, rnn_size, num_layers,
                                                       target_vocab_to_int, target_vocab_size,
                                                       batch_size, keep_prob, dec_embedding_size)
    
    return training_output, inference_output


"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_seq2seq_model(seq2seq_model)


Tests Passed

Neural Network Training

Hyperparameters

Tune the following parameters:

  • Set epochs to the number of epochs.
  • Set batch_size to the batch size.
  • Set rnn_size to the size of the RNNs.
  • Set num_layers to the number of layers.
  • Set encoding_embedding_size to the size of the embedding for the encoder.
  • Set decoding_embedding_size to the size of the embedding for the decoder.
  • Set learning_rate to the learning rate.
  • Set keep_probability to the Dropout keep probability
  • Set display_step to state how many steps between each debug output statement

In [33]:
# Number of Epochs
epochs = 10

# Batch Size
batch_size = 134

# RNN Size
rnn_size = 512

# Number of Layers
num_layers = 2

# Embedding Size
encoding_embedding_size = 269
decoding_embedding_size = 269

# Learning Rate
learning_rate = 0.001

# Dropout Keep Probability
keep_probability = 0.8
display_step = 25

Build the Graph

Build the graph using the neural network you implemented.


In [34]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
save_path = 'checkpoints/dev'
(source_int_text, target_int_text), (source_vocab_to_int, target_vocab_to_int), _ = helper.load_preprocess()
max_target_sentence_length = max([len(sentence) for sentence in source_int_text])

train_graph = tf.Graph()
with train_graph.as_default():
    input_data, targets, lr, keep_prob, target_sequence_length, max_target_sequence_length, source_sequence_length = model_inputs()

    #sequence_length = tf.placeholder_with_default(max_target_sentence_length, None, name='sequence_length')
    input_shape = tf.shape(input_data)

    train_logits, inference_logits = seq2seq_model(tf.reverse(input_data, [-1]),
                                                   targets,
                                                   keep_prob,
                                                   batch_size,
                                                   source_sequence_length,
                                                   target_sequence_length,
                                                   max_target_sequence_length,
                                                   len(source_vocab_to_int),
                                                   len(target_vocab_to_int),
                                                   encoding_embedding_size,
                                                   decoding_embedding_size,
                                                   rnn_size,
                                                   num_layers,
                                                   target_vocab_to_int)


    training_logits = tf.identity(train_logits.rnn_output, name='logits')
    inference_logits = tf.identity(inference_logits.sample_id, name='predictions')

    masks = tf.sequence_mask(target_sequence_length, max_target_sequence_length, dtype=tf.float32, name='masks')

    with tf.name_scope("optimization"):
        # Loss function
        cost = tf.contrib.seq2seq.sequence_loss(
            training_logits,
            targets,
            masks)

        # Optimizer
        optimizer = tf.train.AdamOptimizer(lr)

        # Gradient Clipping
        gradients = optimizer.compute_gradients(cost)
        capped_gradients = [(tf.clip_by_value(grad, -1., 1.), var) for grad, var in gradients if grad is not None]
        train_op = optimizer.apply_gradients(capped_gradients)

Batch and pad the source and target sequences


In [35]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
def pad_sentence_batch(sentence_batch, pad_int):
    """Pad sentences with <PAD> so that each sentence of a batch has the same length"""
    max_sentence = max([len(sentence) for sentence in sentence_batch])
    return [sentence + [pad_int] * (max_sentence - len(sentence)) for sentence in sentence_batch]


def get_batches(sources, targets, batch_size, source_pad_int, target_pad_int):
    """Batch targets, sources, and the lengths of their sentences together"""
    for batch_i in range(0, len(sources)//batch_size):
        start_i = batch_i * batch_size

        # Slice the right amount for the batch
        sources_batch = sources[start_i:start_i + batch_size]
        targets_batch = targets[start_i:start_i + batch_size]

        # Pad
        pad_sources_batch = np.array(pad_sentence_batch(sources_batch, source_pad_int))
        pad_targets_batch = np.array(pad_sentence_batch(targets_batch, target_pad_int))

        # Need the lengths for the _lengths parameters
        pad_targets_lengths = []
        for target in pad_targets_batch:
            pad_targets_lengths.append(len(target))

        pad_source_lengths = []
        for source in pad_sources_batch:
            pad_source_lengths.append(len(source))

        yield pad_sources_batch, pad_targets_batch, pad_source_lengths, pad_targets_lengths

Train

Train the neural network on the preprocessed data. If you have a hard time getting a good loss, check the forms to see if anyone is having the same problem.


In [36]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
def get_accuracy(target, logits):
    """
    Calculate accuracy
    """
    max_seq = max(target.shape[1], logits.shape[1])
    if max_seq - target.shape[1]:
        target = np.pad(
            target,
            [(0,0),(0,max_seq - target.shape[1])],
            'constant')
    if max_seq - logits.shape[1]:
        logits = np.pad(
            logits,
            [(0,0),(0,max_seq - logits.shape[1])],
            'constant')

    return np.mean(np.equal(target, logits))

# Split data to training and validation sets
train_source = source_int_text[batch_size:]
train_target = target_int_text[batch_size:]
valid_source = source_int_text[:batch_size]
valid_target = target_int_text[:batch_size]
(valid_sources_batch, valid_targets_batch, valid_sources_lengths, valid_targets_lengths ) = next(get_batches(valid_source,
                                                                                                             valid_target,
                                                                                                             batch_size,
                                                                                                             source_vocab_to_int['<PAD>'],
                                                                                                             target_vocab_to_int['<PAD>']))                                                                                                  
with tf.Session(graph=train_graph) as sess:
    sess.run(tf.global_variables_initializer())

    loss_list = []
    valid_acc_list = []

    for epoch_i in range(epochs):
        for batch_i, (source_batch, target_batch, sources_lengths, targets_lengths) in enumerate(
                get_batches(train_source, train_target, batch_size,
                            source_vocab_to_int['<PAD>'],
                            target_vocab_to_int['<PAD>'])):

            _, loss = sess.run(
                [train_op, cost],
                {input_data: source_batch,
                 targets: target_batch,
                 lr: learning_rate,
                 target_sequence_length: targets_lengths,
                 source_sequence_length: sources_lengths,
                 keep_prob: keep_probability})

            loss_list.append(loss)
            if batch_i % display_step == 0 and batch_i > 0:


                batch_train_logits = sess.run(
                    inference_logits,
                    {input_data: source_batch,
                     source_sequence_length: sources_lengths,
                     target_sequence_length: targets_lengths,
                     keep_prob: 1.0})


                batch_valid_logits = sess.run(
                    inference_logits,
                    {input_data: valid_sources_batch,
                     source_sequence_length: valid_sources_lengths,
                     target_sequence_length: valid_targets_lengths,
                     keep_prob: 1.0})

                train_acc = get_accuracy(target_batch, batch_train_logits)

                valid_acc = get_accuracy(valid_targets_batch, batch_valid_logits)
                valid_acc_list.append(valid_acc)

                print('Epoch {:>3} Batch {:>4}/{} - Train Accuracy: {:>6.4f}, Validation Accuracy: {:>6.4f}, Loss: {:>6.4f}'
                      .format(epoch_i, batch_i, len(source_int_text) // batch_size, train_acc, valid_acc, loss))

    # Save Model
    saver = tf.train.Saver()
    saver.save(sess, save_path)
    print('Model Trained and Saved')


Epoch   0 Batch   25/1028 - Train Accuracy: 0.3463, Validation Accuracy: 0.3993, Loss: 2.5808
Epoch   0 Batch   50/1028 - Train Accuracy: 0.4407, Validation Accuracy: 0.4953, Loss: 1.9584
Epoch   0 Batch   75/1028 - Train Accuracy: 0.4116, Validation Accuracy: 0.5075, Loss: 1.5902
Epoch   0 Batch  100/1028 - Train Accuracy: 0.4218, Validation Accuracy: 0.5122, Loss: 1.2501
Epoch   0 Batch  125/1028 - Train Accuracy: 0.4608, Validation Accuracy: 0.4942, Loss: 1.0324
Epoch   0 Batch  150/1028 - Train Accuracy: 0.4787, Validation Accuracy: 0.5153, Loss: 0.9278
Epoch   0 Batch  175/1028 - Train Accuracy: 0.4910, Validation Accuracy: 0.4953, Loss: 0.8233
Epoch   0 Batch  200/1028 - Train Accuracy: 0.5398, Validation Accuracy: 0.5692, Loss: 0.7580
Epoch   0 Batch  225/1028 - Train Accuracy: 0.5988, Validation Accuracy: 0.5865, Loss: 0.6870
Epoch   0 Batch  250/1028 - Train Accuracy: 0.5836, Validation Accuracy: 0.5594, Loss: 0.6756
Epoch   0 Batch  275/1028 - Train Accuracy: 0.5485, Validation Accuracy: 0.5753, Loss: 0.6937
Epoch   0 Batch  300/1028 - Train Accuracy: 0.6020, Validation Accuracy: 0.5845, Loss: 0.6007
Epoch   0 Batch  325/1028 - Train Accuracy: 0.5840, Validation Accuracy: 0.5889, Loss: 0.6188
Epoch   0 Batch  350/1028 - Train Accuracy: 0.5451, Validation Accuracy: 0.5957, Loss: 0.5894
Epoch   0 Batch  375/1028 - Train Accuracy: 0.5754, Validation Accuracy: 0.6140, Loss: 0.5883
Epoch   0 Batch  400/1028 - Train Accuracy: 0.5698, Validation Accuracy: 0.6099, Loss: 0.5797
Epoch   0 Batch  425/1028 - Train Accuracy: 0.5632, Validation Accuracy: 0.6058, Loss: 0.5872
Epoch   0 Batch  450/1028 - Train Accuracy: 0.6254, Validation Accuracy: 0.6364, Loss: 0.5597
Epoch   0 Batch  475/1028 - Train Accuracy: 0.5989, Validation Accuracy: 0.6350, Loss: 0.5559
Epoch   0 Batch  500/1028 - Train Accuracy: 0.6302, Validation Accuracy: 0.6442, Loss: 0.5005
Epoch   0 Batch  525/1028 - Train Accuracy: 0.6284, Validation Accuracy: 0.6194, Loss: 0.5358
Epoch   0 Batch  550/1028 - Train Accuracy: 0.6673, Validation Accuracy: 0.6645, Loss: 0.4778
Epoch   0 Batch  575/1028 - Train Accuracy: 0.6422, Validation Accuracy: 0.6316, Loss: 0.4401
Epoch   0 Batch  600/1028 - Train Accuracy: 0.6481, Validation Accuracy: 0.6567, Loss: 0.4661
Epoch   0 Batch  625/1028 - Train Accuracy: 0.6754, Validation Accuracy: 0.6811, Loss: 0.4122
Epoch   0 Batch  650/1028 - Train Accuracy: 0.7367, Validation Accuracy: 0.6988, Loss: 0.3666
Epoch   0 Batch  675/1028 - Train Accuracy: 0.7149, Validation Accuracy: 0.7215, Loss: 0.3703
Epoch   0 Batch  700/1028 - Train Accuracy: 0.7791, Validation Accuracy: 0.7303, Loss: 0.3558
Epoch   0 Batch  725/1028 - Train Accuracy: 0.7953, Validation Accuracy: 0.7391, Loss: 0.2972
Epoch   0 Batch  750/1028 - Train Accuracy: 0.8134, Validation Accuracy: 0.7619, Loss: 0.3007
Epoch   0 Batch  775/1028 - Train Accuracy: 0.7560, Validation Accuracy: 0.7466, Loss: 0.3229
Epoch   0 Batch  800/1028 - Train Accuracy: 0.7787, Validation Accuracy: 0.7904, Loss: 0.2898
Epoch   0 Batch  825/1028 - Train Accuracy: 0.8112, Validation Accuracy: 0.7965, Loss: 0.2674
Epoch   0 Batch  850/1028 - Train Accuracy: 0.8369, Validation Accuracy: 0.8138, Loss: 0.2370
Epoch   0 Batch  875/1028 - Train Accuracy: 0.8183, Validation Accuracy: 0.8239, Loss: 0.2378
Epoch   0 Batch  900/1028 - Train Accuracy: 0.8157, Validation Accuracy: 0.7965, Loss: 0.2402
Epoch   0 Batch  925/1028 - Train Accuracy: 0.8078, Validation Accuracy: 0.8253, Loss: 0.2486
Epoch   0 Batch  950/1028 - Train Accuracy: 0.8611, Validation Accuracy: 0.8148, Loss: 0.1881
Epoch   0 Batch  975/1028 - Train Accuracy: 0.8507, Validation Accuracy: 0.8477, Loss: 0.1832
Epoch   0 Batch 1000/1028 - Train Accuracy: 0.8463, Validation Accuracy: 0.8606, Loss: 0.1956
Epoch   0 Batch 1025/1028 - Train Accuracy: 0.8843, Validation Accuracy: 0.8355, Loss: 0.1723
Epoch   1 Batch   25/1028 - Train Accuracy: 0.8295, Validation Accuracy: 0.8589, Loss: 0.1713
Epoch   1 Batch   50/1028 - Train Accuracy: 0.9052, Validation Accuracy: 0.8602, Loss: 0.1371
Epoch   1 Batch   75/1028 - Train Accuracy: 0.8476, Validation Accuracy: 0.8606, Loss: 0.1535
Epoch   1 Batch  100/1028 - Train Accuracy: 0.8716, Validation Accuracy: 0.8647, Loss: 0.1445
Epoch   1 Batch  125/1028 - Train Accuracy: 0.8873, Validation Accuracy: 0.8833, Loss: 0.1308
Epoch   1 Batch  150/1028 - Train Accuracy: 0.8974, Validation Accuracy: 0.8657, Loss: 0.1136
Epoch   1 Batch  175/1028 - Train Accuracy: 0.9123, Validation Accuracy: 0.8830, Loss: 0.1131
Epoch   1 Batch  200/1028 - Train Accuracy: 0.9094, Validation Accuracy: 0.9071, Loss: 0.1115
Epoch   1 Batch  225/1028 - Train Accuracy: 0.9208, Validation Accuracy: 0.8867, Loss: 0.1034
Epoch   1 Batch  250/1028 - Train Accuracy: 0.9384, Validation Accuracy: 0.8962, Loss: 0.1004
Epoch   1 Batch  275/1028 - Train Accuracy: 0.8888, Validation Accuracy: 0.8820, Loss: 0.1172
Epoch   1 Batch  300/1028 - Train Accuracy: 0.9314, Validation Accuracy: 0.8979, Loss: 0.0930
Epoch   1 Batch  325/1028 - Train Accuracy: 0.9549, Validation Accuracy: 0.8877, Loss: 0.0734
Epoch   1 Batch  350/1028 - Train Accuracy: 0.9147, Validation Accuracy: 0.8857, Loss: 0.1019
Epoch   1 Batch  375/1028 - Train Accuracy: 0.9201, Validation Accuracy: 0.8850, Loss: 0.0939
Epoch   1 Batch  400/1028 - Train Accuracy: 0.9321, Validation Accuracy: 0.8965, Loss: 0.0873
Epoch   1 Batch  425/1028 - Train Accuracy: 0.8743, Validation Accuracy: 0.8836, Loss: 0.0995
Epoch   1 Batch  450/1028 - Train Accuracy: 0.9578, Validation Accuracy: 0.8884, Loss: 0.0759
Epoch   1 Batch  475/1028 - Train Accuracy: 0.9250, Validation Accuracy: 0.8874, Loss: 0.0846
Epoch   1 Batch  500/1028 - Train Accuracy: 0.9272, Validation Accuracy: 0.9101, Loss: 0.0814
Epoch   1 Batch  525/1028 - Train Accuracy: 0.8664, Validation Accuracy: 0.9074, Loss: 0.1048
Epoch   1 Batch  550/1028 - Train Accuracy: 0.9324, Validation Accuracy: 0.9013, Loss: 0.0714
Epoch   1 Batch  575/1028 - Train Accuracy: 0.9246, Validation Accuracy: 0.9121, Loss: 0.0678
Epoch   1 Batch  600/1028 - Train Accuracy: 0.9120, Validation Accuracy: 0.9111, Loss: 0.0714
Epoch   1 Batch  625/1028 - Train Accuracy: 0.9362, Validation Accuracy: 0.9301, Loss: 0.0634
Epoch   1 Batch  650/1028 - Train Accuracy: 0.9179, Validation Accuracy: 0.9084, Loss: 0.0653
Epoch   1 Batch  675/1028 - Train Accuracy: 0.9164, Validation Accuracy: 0.8938, Loss: 0.0781
Epoch   1 Batch  700/1028 - Train Accuracy: 0.9157, Validation Accuracy: 0.9074, Loss: 0.0744
Epoch   1 Batch  725/1028 - Train Accuracy: 0.9485, Validation Accuracy: 0.9108, Loss: 0.0652
Epoch   1 Batch  750/1028 - Train Accuracy: 0.9382, Validation Accuracy: 0.8942, Loss: 0.0556
Epoch   1 Batch  775/1028 - Train Accuracy: 0.9313, Validation Accuracy: 0.9050, Loss: 0.0765
Epoch   1 Batch  800/1028 - Train Accuracy: 0.9269, Validation Accuracy: 0.9308, Loss: 0.0690
Epoch   1 Batch  825/1028 - Train Accuracy: 0.9056, Validation Accuracy: 0.9050, Loss: 0.0743
Epoch   1 Batch  850/1028 - Train Accuracy: 0.9442, Validation Accuracy: 0.9155, Loss: 0.0630
Epoch   1 Batch  875/1028 - Train Accuracy: 0.9332, Validation Accuracy: 0.9230, Loss: 0.0672
Epoch   1 Batch  900/1028 - Train Accuracy: 0.9302, Validation Accuracy: 0.9132, Loss: 0.0630
Epoch   1 Batch  925/1028 - Train Accuracy: 0.9328, Validation Accuracy: 0.9206, Loss: 0.0677
Epoch   1 Batch  950/1028 - Train Accuracy: 0.9534, Validation Accuracy: 0.9318, Loss: 0.0452
Epoch   1 Batch  975/1028 - Train Accuracy: 0.9296, Validation Accuracy: 0.9237, Loss: 0.0513
Epoch   1 Batch 1000/1028 - Train Accuracy: 0.9328, Validation Accuracy: 0.9318, Loss: 0.0548
Epoch   1 Batch 1025/1028 - Train Accuracy: 0.9593, Validation Accuracy: 0.9372, Loss: 0.0532
Epoch   2 Batch   25/1028 - Train Accuracy: 0.9261, Validation Accuracy: 0.9088, Loss: 0.0563
Epoch   2 Batch   50/1028 - Train Accuracy: 0.9511, Validation Accuracy: 0.9121, Loss: 0.0470
Epoch   2 Batch   75/1028 - Train Accuracy: 0.9478, Validation Accuracy: 0.9271, Loss: 0.0504
Epoch   2 Batch  100/1028 - Train Accuracy: 0.9560, Validation Accuracy: 0.9179, Loss: 0.0470
Epoch   2 Batch  125/1028 - Train Accuracy: 0.9362, Validation Accuracy: 0.9308, Loss: 0.0561
Epoch   2 Batch  150/1028 - Train Accuracy: 0.9522, Validation Accuracy: 0.9274, Loss: 0.0395
Epoch   2 Batch  175/1028 - Train Accuracy: 0.9549, Validation Accuracy: 0.9288, Loss: 0.0391
Epoch   2 Batch  200/1028 - Train Accuracy: 0.9641, Validation Accuracy: 0.9311, Loss: 0.0376
Epoch   2 Batch  225/1028 - Train Accuracy: 0.9446, Validation Accuracy: 0.9294, Loss: 0.0423
Epoch   2 Batch  250/1028 - Train Accuracy: 0.9646, Validation Accuracy: 0.9515, Loss: 0.0366
Epoch   2 Batch  275/1028 - Train Accuracy: 0.9336, Validation Accuracy: 0.9162, Loss: 0.0552
Epoch   2 Batch  300/1028 - Train Accuracy: 0.9502, Validation Accuracy: 0.9349, Loss: 0.0417
Epoch   2 Batch  325/1028 - Train Accuracy: 0.9776, Validation Accuracy: 0.9467, Loss: 0.0331
Epoch   2 Batch  350/1028 - Train Accuracy: 0.9641, Validation Accuracy: 0.9199, Loss: 0.0302
Epoch   2 Batch  375/1028 - Train Accuracy: 0.9455, Validation Accuracy: 0.9257, Loss: 0.0447
Epoch   2 Batch  400/1028 - Train Accuracy: 0.9362, Validation Accuracy: 0.9047, Loss: 0.0829
Epoch   2 Batch  425/1028 - Train Accuracy: 0.9214, Validation Accuracy: 0.9077, Loss: 0.0677
Epoch   2 Batch  450/1028 - Train Accuracy: 0.9675, Validation Accuracy: 0.9128, Loss: 0.0474
Epoch   2 Batch  475/1028 - Train Accuracy: 0.9384, Validation Accuracy: 0.9281, Loss: 0.0470
Epoch   2 Batch  500/1028 - Train Accuracy: 0.9534, Validation Accuracy: 0.9172, Loss: 0.0447
Epoch   2 Batch  525/1028 - Train Accuracy: 0.9418, Validation Accuracy: 0.9230, Loss: 0.0438
Epoch   2 Batch  550/1028 - Train Accuracy: 0.9721, Validation Accuracy: 0.9179, Loss: 0.0353
Epoch   2 Batch  575/1028 - Train Accuracy: 0.9511, Validation Accuracy: 0.9345, Loss: 0.0429
Epoch   2 Batch  600/1028 - Train Accuracy: 0.9501, Validation Accuracy: 0.9600, Loss: 0.0464
Epoch   2 Batch  625/1028 - Train Accuracy: 0.9683, Validation Accuracy: 0.9366, Loss: 0.0340
Epoch   2 Batch  650/1028 - Train Accuracy: 0.9385, Validation Accuracy: 0.9542, Loss: 0.0368
Epoch   2 Batch  675/1028 - Train Accuracy: 0.9373, Validation Accuracy: 0.9277, Loss: 0.0419
Epoch   2 Batch  700/1028 - Train Accuracy: 0.9444, Validation Accuracy: 0.9305, Loss: 0.0446
Epoch   2 Batch  725/1028 - Train Accuracy: 0.9524, Validation Accuracy: 0.9244, Loss: 0.0350
Epoch   2 Batch  750/1028 - Train Accuracy: 0.9520, Validation Accuracy: 0.9193, Loss: 0.0310
Epoch   2 Batch  775/1028 - Train Accuracy: 0.9414, Validation Accuracy: 0.9274, Loss: 0.0461
Epoch   2 Batch  800/1028 - Train Accuracy: 0.9571, Validation Accuracy: 0.9244, Loss: 0.0418
Epoch   2 Batch  825/1028 - Train Accuracy: 0.9493, Validation Accuracy: 0.9471, Loss: 0.0334
Epoch   2 Batch  850/1028 - Train Accuracy: 0.9620, Validation Accuracy: 0.9281, Loss: 0.0334
Epoch   2 Batch  875/1028 - Train Accuracy: 0.9537, Validation Accuracy: 0.9386, Loss: 0.0401
Epoch   2 Batch  900/1028 - Train Accuracy: 0.9354, Validation Accuracy: 0.9281, Loss: 0.0409
Epoch   2 Batch  925/1028 - Train Accuracy: 0.9485, Validation Accuracy: 0.9339, Loss: 0.0414
Epoch   2 Batch  950/1028 - Train Accuracy: 0.9542, Validation Accuracy: 0.9355, Loss: 0.0322
Epoch   2 Batch  975/1028 - Train Accuracy: 0.9616, Validation Accuracy: 0.9515, Loss: 0.0313
Epoch   2 Batch 1000/1028 - Train Accuracy: 0.9709, Validation Accuracy: 0.9376, Loss: 0.0355
Epoch   2 Batch 1025/1028 - Train Accuracy: 0.9627, Validation Accuracy: 0.9471, Loss: 0.0317
Epoch   3 Batch   25/1028 - Train Accuracy: 0.9500, Validation Accuracy: 0.9484, Loss: 0.0388
Epoch   3 Batch   50/1028 - Train Accuracy: 0.9429, Validation Accuracy: 0.9478, Loss: 0.0287
Epoch   3 Batch   75/1028 - Train Accuracy: 0.9682, Validation Accuracy: 0.9406, Loss: 0.0257
Epoch   3 Batch  100/1028 - Train Accuracy: 0.9741, Validation Accuracy: 0.9427, Loss: 0.0329
Epoch   3 Batch  125/1028 - Train Accuracy: 0.9474, Validation Accuracy: 0.9539, Loss: 0.0240
Epoch   3 Batch  150/1028 - Train Accuracy: 0.9619, Validation Accuracy: 0.9549, Loss: 0.0250
Epoch   3 Batch  175/1028 - Train Accuracy: 0.9646, Validation Accuracy: 0.9515, Loss: 0.0324
Epoch   3 Batch  200/1028 - Train Accuracy: 0.9776, Validation Accuracy: 0.9512, Loss: 0.0253
Epoch   3 Batch  225/1028 - Train Accuracy: 0.9666, Validation Accuracy: 0.9518, Loss: 0.0340
Epoch   3 Batch  250/1028 - Train Accuracy: 0.9750, Validation Accuracy: 0.9542, Loss: 0.0278
Epoch   3 Batch  275/1028 - Train Accuracy: 0.9627, Validation Accuracy: 0.9678, Loss: 0.0443
Epoch   3 Batch  300/1028 - Train Accuracy: 0.9812, Validation Accuracy: 0.9528, Loss: 0.0302
Epoch   3 Batch  325/1028 - Train Accuracy: 0.9646, Validation Accuracy: 0.9484, Loss: 0.0298
Epoch   3 Batch  350/1028 - Train Accuracy: 0.9801, Validation Accuracy: 0.9328, Loss: 0.0288
Epoch   3 Batch  375/1028 - Train Accuracy: 0.9694, Validation Accuracy: 0.9467, Loss: 0.0249
Epoch   3 Batch  400/1028 - Train Accuracy: 0.9683, Validation Accuracy: 0.9322, Loss: 0.0293
Epoch   3 Batch  425/1028 - Train Accuracy: 0.9599, Validation Accuracy: 0.9244, Loss: 0.0283
Epoch   3 Batch  450/1028 - Train Accuracy: 0.9683, Validation Accuracy: 0.9437, Loss: 0.0328
Epoch   3 Batch  475/1028 - Train Accuracy: 0.9515, Validation Accuracy: 0.9315, Loss: 0.0402
Epoch   3 Batch  500/1028 - Train Accuracy: 0.9754, Validation Accuracy: 0.9420, Loss: 0.0276
Epoch   3 Batch  525/1028 - Train Accuracy: 0.9448, Validation Accuracy: 0.9383, Loss: 0.0318
Epoch   3 Batch  550/1028 - Train Accuracy: 0.9756, Validation Accuracy: 0.9284, Loss: 0.0235
Epoch   3 Batch  575/1028 - Train Accuracy: 0.9675, Validation Accuracy: 0.9339, Loss: 0.0318
Epoch   3 Batch  600/1028 - Train Accuracy: 0.9749, Validation Accuracy: 0.9556, Loss: 0.0301
Epoch   3 Batch  625/1028 - Train Accuracy: 0.9668, Validation Accuracy: 0.9454, Loss: 0.0284
Epoch   3 Batch  650/1028 - Train Accuracy: 0.9552, Validation Accuracy: 0.9447, Loss: 0.0309
Epoch   3 Batch  675/1028 - Train Accuracy: 0.9604, Validation Accuracy: 0.9593, Loss: 0.0312
Epoch   3 Batch  700/1028 - Train Accuracy: 0.9724, Validation Accuracy: 0.9569, Loss: 0.0232
Epoch   3 Batch  725/1028 - Train Accuracy: 0.9733, Validation Accuracy: 0.9372, Loss: 0.0281
Epoch   3 Batch  750/1028 - Train Accuracy: 0.9794, Validation Accuracy: 0.9423, Loss: 0.0226
Epoch   3 Batch  775/1028 - Train Accuracy: 0.9657, Validation Accuracy: 0.9484, Loss: 0.0287
Epoch   3 Batch  800/1028 - Train Accuracy: 0.9716, Validation Accuracy: 0.9539, Loss: 0.0295
Epoch   3 Batch  825/1028 - Train Accuracy: 0.9560, Validation Accuracy: 0.9691, Loss: 0.0274
Epoch   3 Batch  850/1028 - Train Accuracy: 0.9623, Validation Accuracy: 0.9579, Loss: 0.0206
Epoch   3 Batch  875/1028 - Train Accuracy: 0.9657, Validation Accuracy: 0.9569, Loss: 0.0226
Epoch   3 Batch  900/1028 - Train Accuracy: 0.9481, Validation Accuracy: 0.9556, Loss: 0.0280
Epoch   3 Batch  925/1028 - Train Accuracy: 0.9470, Validation Accuracy: 0.9545, Loss: 0.0283
Epoch   3 Batch  950/1028 - Train Accuracy: 0.9879, Validation Accuracy: 0.9498, Loss: 0.0190
Epoch   3 Batch  975/1028 - Train Accuracy: 0.9538, Validation Accuracy: 0.9545, Loss: 0.0247
Epoch   3 Batch 1000/1028 - Train Accuracy: 0.9847, Validation Accuracy: 0.9345, Loss: 0.0245
Epoch   3 Batch 1025/1028 - Train Accuracy: 0.9787, Validation Accuracy: 0.9501, Loss: 0.0239
Epoch   4 Batch   25/1028 - Train Accuracy: 0.9567, Validation Accuracy: 0.9623, Loss: 0.0299
Epoch   4 Batch   50/1028 - Train Accuracy: 0.9575, Validation Accuracy: 0.9630, Loss: 0.0263
Epoch   4 Batch   75/1028 - Train Accuracy: 0.9819, Validation Accuracy: 0.9620, Loss: 0.0218
Epoch   4 Batch  100/1028 - Train Accuracy: 0.9772, Validation Accuracy: 0.9437, Loss: 0.0244
Epoch   4 Batch  125/1028 - Train Accuracy: 0.9511, Validation Accuracy: 0.9437, Loss: 0.0232
Epoch   4 Batch  150/1028 - Train Accuracy: 0.9653, Validation Accuracy: 0.9668, Loss: 0.0233
Epoch   4 Batch  175/1028 - Train Accuracy: 0.9746, Validation Accuracy: 0.9623, Loss: 0.0268
Epoch   4 Batch  200/1028 - Train Accuracy: 0.9705, Validation Accuracy: 0.9545, Loss: 0.0255
Epoch   4 Batch  225/1028 - Train Accuracy: 0.9723, Validation Accuracy: 0.9579, Loss: 0.0259
Epoch   4 Batch  250/1028 - Train Accuracy: 0.9862, Validation Accuracy: 0.9573, Loss: 0.0264
Epoch   4 Batch  275/1028 - Train Accuracy: 0.9664, Validation Accuracy: 0.9450, Loss: 0.0605
Epoch   4 Batch  300/1028 - Train Accuracy: 0.9790, Validation Accuracy: 0.9328, Loss: 0.0210
Epoch   4 Batch  325/1028 - Train Accuracy: 0.9840, Validation Accuracy: 0.9522, Loss: 0.0217
Epoch   4 Batch  350/1028 - Train Accuracy: 0.9815, Validation Accuracy: 0.9467, Loss: 0.0168
Epoch   4 Batch  375/1028 - Train Accuracy: 0.9578, Validation Accuracy: 0.9634, Loss: 0.0248
Epoch   4 Batch  400/1028 - Train Accuracy: 0.9616, Validation Accuracy: 0.9467, Loss: 0.0214
Epoch   4 Batch  425/1028 - Train Accuracy: 0.9639, Validation Accuracy: 0.9495, Loss: 0.0214
Epoch   4 Batch  450/1028 - Train Accuracy: 0.9769, Validation Accuracy: 0.9525, Loss: 0.0231
Epoch   4 Batch  475/1028 - Train Accuracy: 0.9653, Validation Accuracy: 0.9393, Loss: 0.0291
Epoch   4 Batch  500/1028 - Train Accuracy: 0.9761, Validation Accuracy: 0.9644, Loss: 0.0199
Epoch   4 Batch  525/1028 - Train Accuracy: 0.9743, Validation Accuracy: 0.9508, Loss: 0.0235
Epoch   4 Batch  550/1028 - Train Accuracy: 0.9792, Validation Accuracy: 0.9488, Loss: 0.0172
Epoch   4 Batch  575/1028 - Train Accuracy: 0.9463, Validation Accuracy: 0.9681, Loss: 0.0251
Epoch   4 Batch  600/1028 - Train Accuracy: 0.9843, Validation Accuracy: 0.9657, Loss: 0.0255
Epoch   4 Batch  625/1028 - Train Accuracy: 0.9787, Validation Accuracy: 0.9674, Loss: 0.0221
Epoch   4 Batch  650/1028 - Train Accuracy: 0.9694, Validation Accuracy: 0.9644, Loss: 0.0261
Epoch   4 Batch  675/1028 - Train Accuracy: 0.9616, Validation Accuracy: 0.9729, Loss: 0.0254
Epoch   4 Batch  700/1028 - Train Accuracy: 0.9672, Validation Accuracy: 0.9491, Loss: 0.0245
Epoch   4 Batch  725/1028 - Train Accuracy: 0.9837, Validation Accuracy: 0.9617, Loss: 0.0210
Epoch   4 Batch  750/1028 - Train Accuracy: 0.9837, Validation Accuracy: 0.9491, Loss: 0.0239
Epoch   4 Batch  775/1028 - Train Accuracy: 0.9728, Validation Accuracy: 0.9661, Loss: 0.0204
Epoch   4 Batch  800/1028 - Train Accuracy: 0.9784, Validation Accuracy: 0.9576, Loss: 0.0222
Epoch   4 Batch  825/1028 - Train Accuracy: 0.9623, Validation Accuracy: 0.9715, Loss: 0.0253
Epoch   4 Batch  850/1028 - Train Accuracy: 0.9670, Validation Accuracy: 0.9647, Loss: 0.0211
Epoch   4 Batch  875/1028 - Train Accuracy: 0.9746, Validation Accuracy: 0.9688, Loss: 0.0194
Epoch   4 Batch  900/1028 - Train Accuracy: 0.9657, Validation Accuracy: 0.9596, Loss: 0.0254
Epoch   4 Batch  925/1028 - Train Accuracy: 0.9646, Validation Accuracy: 0.9593, Loss: 0.0230
Epoch   4 Batch  950/1028 - Train Accuracy: 0.9911, Validation Accuracy: 0.9434, Loss: 0.0185
Epoch   4 Batch  975/1028 - Train Accuracy: 0.9623, Validation Accuracy: 0.9640, Loss: 0.0252
Epoch   4 Batch 1000/1028 - Train Accuracy: 0.9888, Validation Accuracy: 0.9640, Loss: 0.0232
Epoch   4 Batch 1025/1028 - Train Accuracy: 0.9787, Validation Accuracy: 0.9780, Loss: 0.0206
Epoch   5 Batch   25/1028 - Train Accuracy: 0.9575, Validation Accuracy: 0.9780, Loss: 0.0236
Epoch   5 Batch   50/1028 - Train Accuracy: 0.9616, Validation Accuracy: 0.9661, Loss: 0.0129
Epoch   5 Batch   75/1028 - Train Accuracy: 0.9776, Validation Accuracy: 0.9505, Loss: 0.0182
Epoch   5 Batch  100/1028 - Train Accuracy: 0.9886, Validation Accuracy: 0.9430, Loss: 0.0209
Epoch   5 Batch  125/1028 - Train Accuracy: 0.9571, Validation Accuracy: 0.9718, Loss: 0.0210
Epoch   5 Batch  150/1028 - Train Accuracy: 0.9843, Validation Accuracy: 0.9600, Loss: 0.0203
Epoch   5 Batch  175/1028 - Train Accuracy: 0.9813, Validation Accuracy: 0.9627, Loss: 0.0215
Epoch   5 Batch  200/1028 - Train Accuracy: 0.9837, Validation Accuracy: 0.9620, Loss: 0.0230
Epoch   5 Batch  225/1028 - Train Accuracy: 0.9659, Validation Accuracy: 0.9613, Loss: 0.0191
Epoch   5 Batch  250/1028 - Train Accuracy: 0.9970, Validation Accuracy: 0.9763, Loss: 0.0120
Epoch   5 Batch  275/1028 - Train Accuracy: 0.9668, Validation Accuracy: 0.9688, Loss: 0.0210
Epoch   5 Batch  300/1028 - Train Accuracy: 0.9904, Validation Accuracy: 0.9640, Loss: 0.0136
Epoch   5 Batch  325/1028 - Train Accuracy: 0.9795, Validation Accuracy: 0.9651, Loss: 0.0177
Epoch   5 Batch  350/1028 - Train Accuracy: 0.9744, Validation Accuracy: 0.9657, Loss: 0.0228
Epoch   5 Batch  375/1028 - Train Accuracy: 0.9724, Validation Accuracy: 0.9552, Loss: 0.0277
Epoch   5 Batch  400/1028 - Train Accuracy: 0.9634, Validation Accuracy: 0.9569, Loss: 0.0196
Epoch   5 Batch  425/1028 - Train Accuracy: 0.9780, Validation Accuracy: 0.9552, Loss: 0.0225
Epoch   5 Batch  450/1028 - Train Accuracy: 0.9813, Validation Accuracy: 0.9549, Loss: 0.0265
Epoch   5 Batch  475/1028 - Train Accuracy: 0.9515, Validation Accuracy: 0.9467, Loss: 0.0365
Epoch   5 Batch  500/1028 - Train Accuracy: 0.9817, Validation Accuracy: 0.9664, Loss: 0.0194
Epoch   5 Batch  525/1028 - Train Accuracy: 0.9810, Validation Accuracy: 0.9532, Loss: 0.0177
Epoch   5 Batch  550/1028 - Train Accuracy: 0.9894, Validation Accuracy: 0.9644, Loss: 0.0149
Epoch   5 Batch  575/1028 - Train Accuracy: 0.9750, Validation Accuracy: 0.9664, Loss: 0.0240
Epoch   5 Batch  600/1028 - Train Accuracy: 0.9937, Validation Accuracy: 0.9607, Loss: 0.0134
Epoch   5 Batch  625/1028 - Train Accuracy: 0.9813, Validation Accuracy: 0.9688, Loss: 0.0180
Epoch   5 Batch  650/1028 - Train Accuracy: 0.9797, Validation Accuracy: 0.9732, Loss: 0.0191
Epoch   5 Batch  675/1028 - Train Accuracy: 0.9728, Validation Accuracy: 0.9640, Loss: 0.0260
Epoch   5 Batch  700/1028 - Train Accuracy: 0.9672, Validation Accuracy: 0.9634, Loss: 0.0188
Epoch   5 Batch  725/1028 - Train Accuracy: 0.9773, Validation Accuracy: 0.9512, Loss: 0.0171
Epoch   5 Batch  750/1028 - Train Accuracy: 0.9808, Validation Accuracy: 0.9545, Loss: 0.0157
Epoch   5 Batch  775/1028 - Train Accuracy: 0.9761, Validation Accuracy: 0.9695, Loss: 0.0243
Epoch   5 Batch  800/1028 - Train Accuracy: 0.9403, Validation Accuracy: 0.9420, Loss: 0.0504
Epoch   5 Batch  825/1028 - Train Accuracy: 0.9743, Validation Accuracy: 0.9593, Loss: 0.0297
Epoch   5 Batch  850/1028 - Train Accuracy: 0.9627, Validation Accuracy: 0.9474, Loss: 0.0209
Epoch   5 Batch  875/1028 - Train Accuracy: 0.9642, Validation Accuracy: 0.9630, Loss: 0.0170
Epoch   5 Batch  900/1028 - Train Accuracy: 0.9664, Validation Accuracy: 0.9623, Loss: 0.0201
Epoch   5 Batch  925/1028 - Train Accuracy: 0.9646, Validation Accuracy: 0.9678, Loss: 0.0227
Epoch   5 Batch  950/1028 - Train Accuracy: 0.9840, Validation Accuracy: 0.9630, Loss: 0.0139
Epoch   5 Batch  975/1028 - Train Accuracy: 0.9716, Validation Accuracy: 0.9617, Loss: 0.0182
Epoch   5 Batch 1000/1028 - Train Accuracy: 0.9810, Validation Accuracy: 0.9590, Loss: 0.0209
Epoch   5 Batch 1025/1028 - Train Accuracy: 0.9821, Validation Accuracy: 0.9756, Loss: 0.0193
Epoch   6 Batch   25/1028 - Train Accuracy: 0.9660, Validation Accuracy: 0.9681, Loss: 0.0171
Epoch   6 Batch   50/1028 - Train Accuracy: 0.9646, Validation Accuracy: 0.9701, Loss: 0.0184
Epoch   6 Batch   75/1028 - Train Accuracy: 0.9760, Validation Accuracy: 0.9617, Loss: 0.0140
Epoch   6 Batch  100/1028 - Train Accuracy: 0.9827, Validation Accuracy: 0.9569, Loss: 0.0191
Epoch   6 Batch  125/1028 - Train Accuracy: 0.9638, Validation Accuracy: 0.9708, Loss: 0.0173
Epoch   6 Batch  150/1028 - Train Accuracy: 0.9795, Validation Accuracy: 0.9664, Loss: 0.0234
Epoch   6 Batch  175/1028 - Train Accuracy: 0.9802, Validation Accuracy: 0.9562, Loss: 0.0137
Epoch   6 Batch  200/1028 - Train Accuracy: 0.9812, Validation Accuracy: 0.9688, Loss: 0.0119
Epoch   6 Batch  225/1028 - Train Accuracy: 0.9783, Validation Accuracy: 0.9786, Loss: 0.0146
Epoch   6 Batch  250/1028 - Train Accuracy: 0.9970, Validation Accuracy: 0.9685, Loss: 0.0128
Epoch   6 Batch  275/1028 - Train Accuracy: 0.9772, Validation Accuracy: 0.9600, Loss: 0.0220
Epoch   6 Batch  300/1028 - Train Accuracy: 0.9858, Validation Accuracy: 0.9630, Loss: 0.0153
Epoch   6 Batch  325/1028 - Train Accuracy: 0.9866, Validation Accuracy: 0.9661, Loss: 0.0144
Epoch   6 Batch  350/1028 - Train Accuracy: 0.9900, Validation Accuracy: 0.9685, Loss: 0.0128
Epoch   6 Batch  375/1028 - Train Accuracy: 0.9653, Validation Accuracy: 0.9640, Loss: 0.0167
Epoch   6 Batch  400/1028 - Train Accuracy: 0.9743, Validation Accuracy: 0.9698, Loss: 0.0239
Epoch   6 Batch  425/1028 - Train Accuracy: 0.9819, Validation Accuracy: 0.9583, Loss: 0.0147
Epoch   6 Batch  450/1028 - Train Accuracy: 0.9896, Validation Accuracy: 0.9698, Loss: 0.0121
Epoch   6 Batch  475/1028 - Train Accuracy: 0.9530, Validation Accuracy: 0.9712, Loss: 0.0191
Epoch   6 Batch  500/1028 - Train Accuracy: 0.9750, Validation Accuracy: 0.9627, Loss: 0.0157
Epoch   6 Batch  525/1028 - Train Accuracy: 0.9672, Validation Accuracy: 0.9668, Loss: 0.0163
Epoch   6 Batch  550/1028 - Train Accuracy: 0.9847, Validation Accuracy: 0.9678, Loss: 0.0084
Epoch   6 Batch  575/1028 - Train Accuracy: 0.9806, Validation Accuracy: 0.9630, Loss: 0.0159
Epoch   6 Batch  600/1028 - Train Accuracy: 0.9878, Validation Accuracy: 0.9651, Loss: 0.0116
Epoch   6 Batch  625/1028 - Train Accuracy: 0.9914, Validation Accuracy: 0.9685, Loss: 0.0200
Epoch   6 Batch  650/1028 - Train Accuracy: 0.9748, Validation Accuracy: 0.9691, Loss: 0.0144
Epoch   6 Batch  675/1028 - Train Accuracy: 0.9761, Validation Accuracy: 0.9705, Loss: 0.0198
Epoch   6 Batch  700/1028 - Train Accuracy: 0.9530, Validation Accuracy: 0.9603, Loss: 0.0141
Epoch   6 Batch  725/1028 - Train Accuracy: 0.9915, Validation Accuracy: 0.9644, Loss: 0.0168
Epoch   6 Batch  750/1028 - Train Accuracy: 0.9904, Validation Accuracy: 0.9528, Loss: 0.0146
Epoch   6 Batch  775/1028 - Train Accuracy: 0.9735, Validation Accuracy: 0.9671, Loss: 0.0161
Epoch   6 Batch  800/1028 - Train Accuracy: 0.9821, Validation Accuracy: 0.9668, Loss: 0.0138
Epoch   6 Batch  825/1028 - Train Accuracy: 0.9690, Validation Accuracy: 0.9881, Loss: 0.0121
Epoch   6 Batch  850/1028 - Train Accuracy: 0.9673, Validation Accuracy: 0.9695, Loss: 0.0140
Epoch   6 Batch  875/1028 - Train Accuracy: 0.9799, Validation Accuracy: 0.9769, Loss: 0.0150
Epoch   6 Batch  900/1028 - Train Accuracy: 0.9836, Validation Accuracy: 0.9735, Loss: 0.0148
Epoch   6 Batch  925/1028 - Train Accuracy: 0.9787, Validation Accuracy: 0.9586, Loss: 0.0137
Epoch   6 Batch  950/1028 - Train Accuracy: 0.9780, Validation Accuracy: 0.9549, Loss: 0.0106
Epoch   6 Batch  975/1028 - Train Accuracy: 0.9755, Validation Accuracy: 0.9583, Loss: 0.0124
Epoch   6 Batch 1000/1028 - Train Accuracy: 0.9914, Validation Accuracy: 0.9668, Loss: 0.0126
Epoch   6 Batch 1025/1028 - Train Accuracy: 0.9892, Validation Accuracy: 0.9773, Loss: 0.0139
Epoch   7 Batch   25/1028 - Train Accuracy: 0.9799, Validation Accuracy: 0.9623, Loss: 0.0155
Epoch   7 Batch   50/1028 - Train Accuracy: 0.9799, Validation Accuracy: 0.9681, Loss: 0.0116
Epoch   7 Batch   75/1028 - Train Accuracy: 0.9823, Validation Accuracy: 0.9617, Loss: 0.0106
Epoch   7 Batch  100/1028 - Train Accuracy: 0.9910, Validation Accuracy: 0.9491, Loss: 0.0144
Epoch   7 Batch  125/1028 - Train Accuracy: 0.9813, Validation Accuracy: 0.9640, Loss: 0.0115
Epoch   7 Batch  150/1028 - Train Accuracy: 0.9743, Validation Accuracy: 0.9688, Loss: 0.0137
Epoch   7 Batch  175/1028 - Train Accuracy: 0.9854, Validation Accuracy: 0.9695, Loss: 0.0137
Epoch   7 Batch  200/1028 - Train Accuracy: 0.9840, Validation Accuracy: 0.9657, Loss: 0.0132
Epoch   7 Batch  225/1028 - Train Accuracy: 0.9812, Validation Accuracy: 0.9620, Loss: 0.0180
Epoch   7 Batch  250/1028 - Train Accuracy: 0.9989, Validation Accuracy: 0.9705, Loss: 0.0098
Epoch   7 Batch  275/1028 - Train Accuracy: 0.9806, Validation Accuracy: 0.9603, Loss: 0.0203
Epoch   7 Batch  300/1028 - Train Accuracy: 0.9911, Validation Accuracy: 0.9559, Loss: 0.0113
Epoch   7 Batch  325/1028 - Train Accuracy: 0.9907, Validation Accuracy: 0.9644, Loss: 0.0365
Epoch   7 Batch  350/1028 - Train Accuracy: 0.9719, Validation Accuracy: 0.9512, Loss: 0.0210
Epoch   7 Batch  375/1028 - Train Accuracy: 0.9616, Validation Accuracy: 0.9596, Loss: 0.0353
Epoch   7 Batch  400/1028 - Train Accuracy: 0.9776, Validation Accuracy: 0.9610, Loss: 0.0223
Epoch   7 Batch  425/1028 - Train Accuracy: 0.9984, Validation Accuracy: 0.9556, Loss: 0.0275
Epoch   7 Batch  450/1028 - Train Accuracy: 0.9765, Validation Accuracy: 0.9651, Loss: 0.0189
Epoch   7 Batch  475/1028 - Train Accuracy: 0.9560, Validation Accuracy: 0.9647, Loss: 0.0314
Epoch   7 Batch  500/1028 - Train Accuracy: 0.9817, Validation Accuracy: 0.9573, Loss: 0.0255
Epoch   7 Batch  525/1028 - Train Accuracy: 0.9735, Validation Accuracy: 0.9691, Loss: 0.0216
Epoch   7 Batch  550/1028 - Train Accuracy: 0.9847, Validation Accuracy: 0.9562, Loss: 0.0173
Epoch   7 Batch  575/1028 - Train Accuracy: 0.9683, Validation Accuracy: 0.9739, Loss: 0.0219
Epoch   7 Batch  600/1028 - Train Accuracy: 0.9929, Validation Accuracy: 0.9756, Loss: 0.0157
Epoch   7 Batch  625/1028 - Train Accuracy: 0.9970, Validation Accuracy: 0.9559, Loss: 0.0157
Epoch   7 Batch  650/1028 - Train Accuracy: 0.9716, Validation Accuracy: 0.9640, Loss: 0.0156
Epoch   7 Batch  675/1028 - Train Accuracy: 0.9701, Validation Accuracy: 0.9685, Loss: 0.0176
Epoch   7 Batch  700/1028 - Train Accuracy: 0.9791, Validation Accuracy: 0.9542, Loss: 0.0157
Epoch   7 Batch  725/1028 - Train Accuracy: 0.9897, Validation Accuracy: 0.9607, Loss: 0.0119
Epoch   7 Batch  750/1028 - Train Accuracy: 0.9922, Validation Accuracy: 0.9583, Loss: 0.0081
Epoch   7 Batch  775/1028 - Train Accuracy: 0.9840, Validation Accuracy: 0.9688, Loss: 0.0128
Epoch   7 Batch  800/1028 - Train Accuracy: 0.9843, Validation Accuracy: 0.9701, Loss: 0.0126
Epoch   7 Batch  825/1028 - Train Accuracy: 0.9862, Validation Accuracy: 0.9590, Loss: 0.0143
Epoch   7 Batch  850/1028 - Train Accuracy: 0.9769, Validation Accuracy: 0.9620, Loss: 0.0153
Epoch   7 Batch  875/1028 - Train Accuracy: 0.9836, Validation Accuracy: 0.9634, Loss: 0.0119
Epoch   7 Batch  900/1028 - Train Accuracy: 0.9731, Validation Accuracy: 0.9708, Loss: 0.0148
Epoch   7 Batch  925/1028 - Train Accuracy: 0.9724, Validation Accuracy: 0.9478, Loss: 0.0136
Epoch   7 Batch  950/1028 - Train Accuracy: 0.9808, Validation Accuracy: 0.9705, Loss: 0.0105
Epoch   7 Batch  975/1028 - Train Accuracy: 0.9808, Validation Accuracy: 0.9640, Loss: 0.0110
Epoch   7 Batch 1000/1028 - Train Accuracy: 0.9933, Validation Accuracy: 0.9708, Loss: 0.0186
Epoch   7 Batch 1025/1028 - Train Accuracy: 0.9851, Validation Accuracy: 0.9786, Loss: 0.0142
Epoch   8 Batch   25/1028 - Train Accuracy: 0.9828, Validation Accuracy: 0.9630, Loss: 0.0164
Epoch   8 Batch   50/1028 - Train Accuracy: 0.9869, Validation Accuracy: 0.9678, Loss: 0.0146
Epoch   8 Batch   75/1028 - Train Accuracy: 0.9756, Validation Accuracy: 0.9640, Loss: 0.0147
Epoch   8 Batch  100/1028 - Train Accuracy: 0.9768, Validation Accuracy: 0.9657, Loss: 0.0094
Epoch   8 Batch  125/1028 - Train Accuracy: 0.9825, Validation Accuracy: 0.9708, Loss: 0.0136
Epoch   8 Batch  150/1028 - Train Accuracy: 0.9705, Validation Accuracy: 0.9688, Loss: 0.0126
Epoch   8 Batch  175/1028 - Train Accuracy: 0.9978, Validation Accuracy: 0.9715, Loss: 0.0079
Epoch   8 Batch  200/1028 - Train Accuracy: 0.9822, Validation Accuracy: 0.9722, Loss: 0.0143
Epoch   8 Batch  225/1028 - Train Accuracy: 0.9826, Validation Accuracy: 0.9681, Loss: 0.0116
Epoch   8 Batch  250/1028 - Train Accuracy: 0.9978, Validation Accuracy: 0.9759, Loss: 0.0108
Epoch   8 Batch  275/1028 - Train Accuracy: 0.9907, Validation Accuracy: 0.9654, Loss: 0.0178
Epoch   8 Batch  300/1028 - Train Accuracy: 0.9787, Validation Accuracy: 0.9607, Loss: 0.0098
Epoch   8 Batch  325/1028 - Train Accuracy: 0.9862, Validation Accuracy: 0.9681, Loss: 0.0122
Epoch   8 Batch  350/1028 - Train Accuracy: 0.9886, Validation Accuracy: 0.9630, Loss: 0.0102
Epoch   8 Batch  375/1028 - Train Accuracy: 0.9810, Validation Accuracy: 0.9607, Loss: 0.0110
Epoch   8 Batch  400/1028 - Train Accuracy: 0.9851, Validation Accuracy: 0.9613, Loss: 0.0183
Epoch   8 Batch  425/1028 - Train Accuracy: 1.0000, Validation Accuracy: 0.9583, Loss: 0.0073
Epoch   8 Batch  450/1028 - Train Accuracy: 0.9892, Validation Accuracy: 0.9630, Loss: 0.0139
Epoch   8 Batch  475/1028 - Train Accuracy: 0.9526, Validation Accuracy: 0.9552, Loss: 0.0122
Epoch   8 Batch  500/1028 - Train Accuracy: 0.9769, Validation Accuracy: 0.9691, Loss: 0.0111
Epoch   8 Batch  525/1028 - Train Accuracy: 0.9683, Validation Accuracy: 0.9749, Loss: 0.0107
Epoch   8 Batch  550/1028 - Train Accuracy: 0.9772, Validation Accuracy: 0.9681, Loss: 0.0074
Epoch   8 Batch  575/1028 - Train Accuracy: 0.9664, Validation Accuracy: 0.9698, Loss: 0.0157
Epoch   8 Batch  600/1028 - Train Accuracy: 0.9811, Validation Accuracy: 0.9763, Loss: 0.0141
Epoch   8 Batch  625/1028 - Train Accuracy: 0.9940, Validation Accuracy: 0.9637, Loss: 0.0114
Epoch   8 Batch  650/1028 - Train Accuracy: 0.9844, Validation Accuracy: 0.9732, Loss: 0.0088
Epoch   8 Batch  675/1028 - Train Accuracy: 0.9754, Validation Accuracy: 0.9732, Loss: 0.0167
Epoch   8 Batch  700/1028 - Train Accuracy: 0.9701, Validation Accuracy: 0.9695, Loss: 0.0140
Epoch   8 Batch  725/1028 - Train Accuracy: 0.9911, Validation Accuracy: 0.9701, Loss: 0.0098
Epoch   8 Batch  750/1028 - Train Accuracy: 0.9733, Validation Accuracy: 0.9610, Loss: 0.0089
Epoch   8 Batch  775/1028 - Train Accuracy: 0.9769, Validation Accuracy: 0.9661, Loss: 0.0161
Epoch   8 Batch  800/1028 - Train Accuracy: 0.9888, Validation Accuracy: 0.9722, Loss: 0.0124
Epoch   8 Batch  825/1028 - Train Accuracy: 0.9813, Validation Accuracy: 0.9752, Loss: 0.0106
Epoch   8 Batch  850/1028 - Train Accuracy: 0.9751, Validation Accuracy: 0.9691, Loss: 0.0113
Epoch   8 Batch  875/1028 - Train Accuracy: 0.9690, Validation Accuracy: 0.9820, Loss: 0.0174
Epoch   8 Batch  900/1028 - Train Accuracy: 0.9817, Validation Accuracy: 0.9657, Loss: 0.0129
Epoch   8 Batch  925/1028 - Train Accuracy: 0.9765, Validation Accuracy: 0.9763, Loss: 0.0112
Epoch   8 Batch  950/1028 - Train Accuracy: 0.9780, Validation Accuracy: 0.9712, Loss: 0.0101
Epoch   8 Batch  975/1028 - Train Accuracy: 0.9655, Validation Accuracy: 0.9749, Loss: 0.0120
Epoch   8 Batch 1000/1028 - Train Accuracy: 0.9925, Validation Accuracy: 0.9756, Loss: 0.0105
Epoch   8 Batch 1025/1028 - Train Accuracy: 0.9851, Validation Accuracy: 0.9685, Loss: 0.0126
Epoch   9 Batch   25/1028 - Train Accuracy: 0.9896, Validation Accuracy: 0.9732, Loss: 0.0149
Epoch   9 Batch   50/1028 - Train Accuracy: 0.9769, Validation Accuracy: 0.9725, Loss: 0.0136
Epoch   9 Batch   75/1028 - Train Accuracy: 0.9882, Validation Accuracy: 0.9746, Loss: 0.0124
Epoch   9 Batch  100/1028 - Train Accuracy: 0.9835, Validation Accuracy: 0.9725, Loss: 0.0118
Epoch   9 Batch  125/1028 - Train Accuracy: 0.9642, Validation Accuracy: 0.9708, Loss: 0.0092
Epoch   9 Batch  150/1028 - Train Accuracy: 0.9903, Validation Accuracy: 0.9695, Loss: 0.0194
Epoch   9 Batch  175/1028 - Train Accuracy: 0.9907, Validation Accuracy: 0.9766, Loss: 0.0118
Epoch   9 Batch  200/1028 - Train Accuracy: 0.9797, Validation Accuracy: 0.9769, Loss: 0.0125
Epoch   9 Batch  225/1028 - Train Accuracy: 0.9865, Validation Accuracy: 0.9790, Loss: 0.0122
Epoch   9 Batch  250/1028 - Train Accuracy: 0.9914, Validation Accuracy: 0.9881, Loss: 0.0093
Epoch   9 Batch  275/1028 - Train Accuracy: 0.9735, Validation Accuracy: 0.9644, Loss: 0.0155
Epoch   9 Batch  300/1028 - Train Accuracy: 0.9900, Validation Accuracy: 0.9735, Loss: 0.0122
Epoch   9 Batch  325/1028 - Train Accuracy: 0.9922, Validation Accuracy: 0.9718, Loss: 0.0074
Epoch   9 Batch  350/1028 - Train Accuracy: 0.9865, Validation Accuracy: 0.9674, Loss: 0.0081
Epoch   9 Batch  375/1028 - Train Accuracy: 0.9869, Validation Accuracy: 0.9664, Loss: 0.0140
Epoch   9 Batch  400/1028 - Train Accuracy: 0.9840, Validation Accuracy: 0.9678, Loss: 0.0099
Epoch   9 Batch  425/1028 - Train Accuracy: 0.9737, Validation Accuracy: 0.9651, Loss: 0.0087
Epoch   9 Batch  450/1028 - Train Accuracy: 0.9903, Validation Accuracy: 0.9681, Loss: 0.0091
Epoch   9 Batch  475/1028 - Train Accuracy: 0.9799, Validation Accuracy: 0.9729, Loss: 0.0205
Epoch   9 Batch  500/1028 - Train Accuracy: 0.9892, Validation Accuracy: 0.9718, Loss: 0.0129
Epoch   9 Batch  525/1028 - Train Accuracy: 0.9944, Validation Accuracy: 0.9671, Loss: 0.0170
Epoch   9 Batch  550/1028 - Train Accuracy: 0.9878, Validation Accuracy: 0.9607, Loss: 0.0102
Epoch   9 Batch  575/1028 - Train Accuracy: 0.9821, Validation Accuracy: 0.9627, Loss: 0.0175
Epoch   9 Batch  600/1028 - Train Accuracy: 0.9882, Validation Accuracy: 0.9763, Loss: 0.0117
Epoch   9 Batch  625/1028 - Train Accuracy: 0.9959, Validation Accuracy: 0.9678, Loss: 0.0111
Epoch   9 Batch  650/1028 - Train Accuracy: 0.9812, Validation Accuracy: 0.9746, Loss: 0.0131
Epoch   9 Batch  675/1028 - Train Accuracy: 0.9701, Validation Accuracy: 0.9623, Loss: 0.0216
Epoch   9 Batch  700/1028 - Train Accuracy: 0.9646, Validation Accuracy: 0.9539, Loss: 0.0155
Epoch   9 Batch  725/1028 - Train Accuracy: 0.9883, Validation Accuracy: 0.9664, Loss: 0.0088
Epoch   9 Batch  750/1028 - Train Accuracy: 0.9972, Validation Accuracy: 0.9668, Loss: 0.0072
Epoch   9 Batch  775/1028 - Train Accuracy: 0.9840, Validation Accuracy: 0.9705, Loss: 0.0104
Epoch   9 Batch  800/1028 - Train Accuracy: 0.9922, Validation Accuracy: 0.9732, Loss: 0.0078
Epoch   9 Batch  825/1028 - Train Accuracy: 0.9765, Validation Accuracy: 0.9701, Loss: 0.0119
Epoch   9 Batch  850/1028 - Train Accuracy: 0.9719, Validation Accuracy: 0.9678, Loss: 0.0118
Epoch   9 Batch  875/1028 - Train Accuracy: 0.9799, Validation Accuracy: 0.9688, Loss: 0.0103
Epoch   9 Batch  900/1028 - Train Accuracy: 0.9810, Validation Accuracy: 0.9644, Loss: 0.0178
Epoch   9 Batch  925/1028 - Train Accuracy: 0.9772, Validation Accuracy: 0.9674, Loss: 0.0146
Epoch   9 Batch  950/1028 - Train Accuracy: 0.9996, Validation Accuracy: 0.9773, Loss: 0.0120
Epoch   9 Batch  975/1028 - Train Accuracy: 0.9701, Validation Accuracy: 0.9851, Loss: 0.0158
Epoch   9 Batch 1000/1028 - Train Accuracy: 0.9933, Validation Accuracy: 0.9742, Loss: 0.0099
Epoch   9 Batch 1025/1028 - Train Accuracy: 0.9843, Validation Accuracy: 0.9671, Loss: 0.0127
Model Trained and Saved

In [37]:
# Visualize the loss and accuracy
import matplotlib.pyplot as plt
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(18, 6))
ax1.plot(loss_list, color='red')
ax1.set_title('Traning Loss')
ax1.set_ylabel('Loss value')

ax2.plot(valid_acc_list)
ax2.set_xlabel('Iterations')
ax2.set_ylabel('Accuracy')
ax2.set_title('Validation Accuracy')
plt.show()


Save Parameters

Save the batch_size and save_path parameters for inference.


In [38]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
# Save parameters for checkpoint
helper.save_params(save_path)

Checkpoint


In [39]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import tensorflow as tf
import numpy as np
import helper
import problem_unittests as tests

_, (source_vocab_to_int, target_vocab_to_int), (source_int_to_vocab, target_int_to_vocab) = helper.load_preprocess()
load_path = helper.load_params()

Sentence to Sequence

To feed a sentence into the model for translation, you first need to preprocess it. Implement the function sentence_to_seq() to preprocess new sentences.

  • Convert the sentence to lowercase
  • Convert words into ids using vocab_to_int
    • Convert words not in the vocabulary, to the <UNK> word id.

In [40]:
def sentence_to_seq(sentence, vocab_to_int):
    """
    Convert a sentence to a sequence of ids
    :param sentence: String
    :param vocab_to_int: Dictionary to go from the words to an id
    :return: List of word ids
    """
    # Convert the sentence to lowercase
    slower = sentence.lower()

    # Convert words into ids using vocab_to_int
    word_ids = []
    for s in slower.split():
        # Convert words not in the vocabulary, to the <UNK> word id.
        if s not in vocab_to_int:
            s = '<UNK>'
        word_ids.append(vocab_to_int[s])   
    
    return word_ids


"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_sentence_to_seq(sentence_to_seq)


Tests Passed

Translate

This will translate translate_sentence from English to French.


In [48]:
#translate_sentence = 'he saw a old yellow truck .' # il a vu un vieux camion jaune = He saw an old yellow truck
#translate_sentence = 'what a beautiful day'  # californie est beau au mois de hiver = California is beautiful in winter
#translate_sentence = 'what time is it' # chine est sec en septembre , et il = China is dry in September, and
#translate_sentence = 'lets go for a ride' # elle est au volant d' une petite voiture rouge = She is driving a small red car
#translate_sentence = 'lets watch a movie' # elle aime une une voiture rouge = She likes a red car
translate_sentence = 'have a great day' # elle est généralement beau en californie = She is generally beautiful in california



"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
translate_sentence = sentence_to_seq(translate_sentence, source_vocab_to_int)

loaded_graph = tf.Graph()
with tf.Session(graph=loaded_graph) as sess:
    # Load saved model
    loader = tf.train.import_meta_graph(load_path + '.meta')
    loader.restore(sess, load_path)

    input_data = loaded_graph.get_tensor_by_name('input:0')
    logits = loaded_graph.get_tensor_by_name('predictions:0')
    target_sequence_length = loaded_graph.get_tensor_by_name('target_sequence_length:0')
    source_sequence_length = loaded_graph.get_tensor_by_name('source_sequence_length:0')
    keep_prob = loaded_graph.get_tensor_by_name('keep_prob:0')

    translate_logits = sess.run(logits, {input_data: [translate_sentence]*batch_size,
                                         target_sequence_length: [len(translate_sentence)*2]*batch_size,
                                         source_sequence_length: [len(translate_sentence)]*batch_size,
                                         keep_prob: 1.0})[0]

print('Input')
print('  Word Ids:      {}'.format([i for i in translate_sentence]))
print('  English Words: {}'.format([source_int_to_vocab[i] for i in translate_sentence]))

print('\nPrediction')
print('  Word Ids:      {}'.format([i for i in translate_logits]))
print('  French Words: {}'.format(" ".join([target_int_to_vocab[i] for i in translate_logits])))


INFO:tensorflow:Restoring parameters from checkpoints/dev
Input
  Word Ids:      [205, 72, 2, 2]
  English Words: ['have', 'a', '<UNK>', '<UNK>']

Prediction
  Word Ids:      [144, 27, 223, 248, 293, 214, 165, 1]
  French Words: elle est généralement beau en californie . <EOS>

Imperfect Translation

You might notice that some sentences translate better than others. Since the dataset you're using only has a vocabulary of 227 English words of the thousands that you use, you're only going to see good results using these words. For this project, you don't need a perfect translation. However, if you want to create a better translation model, you'll need better data.

You can train on the WMT10 French-English corpus. This dataset has more vocabulary and richer in topics discussed. However, this will take you days to train, so make sure you've a GPU and the neural network is performing well on dataset we provided. Just make sure you play with the WMT10 corpus after you've submitted this project.

Submitting This Project

When submitting this project, make sure to run all the cells before saving the notebook. Save the notebook file as "dlnd_language_translation.ipynb" and save it as a HTML file under "File" -> "Download as". Include the "helper.py" and "problem_unittests.py" files in your submission.